//获取路径携带的信息
var loc = location.href,
    n1 = loc.length,//地址的总长度
    n2 = loc.indexOf('='),//取得=号的位置
    id = decodeURI(loc.substr(n2 + 1, n1 - n2));

    var user = JSON.parse(localStorage.getItem('user'));

var $,
    table;

layui.use(['jquery', 'table'], function () {
    $ = layui.jquery,
        table = layui.table;

    getUseCouponData('');

    //查询用户信息
    confirm(false);
});


function getUseCouponData(couponName){
    console.log(couponName)
    $.ajax({
        url: '/UserCoupon/getAllTable',
        type: 'post',
        dataType: 'json',
        data: {
            'couponName': couponName,
        },
        success: function (item) {
            console.log(item.data)
            getTable(item.data);
        }
    });
};

function getTable(data){
    table.render({
        elem: '#demo',
        data: data,
        toolbar: true,
        page:{//自定义分页
            layout:['count','prev','page','next','limit','skip','refresh'],
            limits:[3,6,9],//分页选项
            limit:4,
            first:"首页",
            last:"尾页",
        },
        cols: [[
            {type: 'checkbox'},
            {field:'couponName',title:'优惠券名称', align:'center'},
            {field:'startDate',title:'金额',align:'center'},
            {field:'',title:'条件使用',align:'center', templet: function (data) {
                    return data.issueQuantity - data.used;
                }},
            {title:'有效期',align:'center', templet:function(data){
                    return "<p>开始：" + data.startDate + "</p>" + '\n'
                        +"<p>结束：" + data.endDate + "</p>";
                }},
        ]]
    });
}

//确定
function confirm(flag) {
    var checkStatus = table.checkStatus('demo');
    if (flag){
        if (checkStatus.data.length > 0){
            checkStatus.data.forEach(function (data){
                $.ajax({
                    url: '/UserCouponUsed/addUserCouponUsed',
                    type: 'post',
                    dataType: 'json',
                    data: {
                        'couponId': data.couponId,
                        'userId': id,
                        'availableDate': data.startDate,
                        'notAvailableDate': data.endDate,
                        'used': data.used + 1,
                        'updateId': user.userId,
                    },
                    success: function (item) {
                        if(item.data){
                            var index = parent.layer.index;
                            parent.layer.close(index);
                            parent.getUseCouponUsedData();
                        }
                    }
                });
            });
        }
    }
}

//搜索
function search () {
    var couponName = $('input[name=couponName]').val();
    console.log(couponName + 1)
    getUseCouponData(couponName)
};

//取消
function resert() {
  var index = parent.layer.index;
  parent.layer.close(index);
};
